package tzjz.example.controller;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import tzjz.example.entity.CyryHistory;
import tzjz.example.mapper.CyryHistoryMapper;
import tzjz.example.service.ICyryHistoryService;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author ForteScarlet
 */
@RestController
@Configuration
@RequestMapping("/reply")
public class ReplyController {

    @Autowired
    private ICyryHistoryService iCyryHistoryService;


    private static String url = "jdbc:mysql://192.168.84.25:3306/ybss?serverTimezone=UTC&useSSL=true&allowPublicKeyRetrieval=true&allowMultiQueries=true";
    private static String username = "root";
    private static String password = "xmzy321";

    @GetMapping("test")
    public void test() throws IOException, InterruptedException {
        List<CyryHistory> list = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            CyryHistory cyryHistory = new CyryHistory();
            cyryHistory.setCyryid(IdUtil.getSnowflakeNextId());
            cyryHistory.setPersonId(IdUtil.getSnowflakeNextId());
            list.add(cyryHistory);
        }

        int listSize = list.size();        //数据集合大小
        int runSize = 4;
        int count = listSize / 4;
        //开启的线程数
        //存放每个线程的执行数据
        ThreadPoolExecutor executor = new ThreadPoolExecutor(runSize, runSize,
                30L, TimeUnit.SECONDS,
                new LinkedBlockingQueue<Runnable>());
        //创建两个个计数器
        CountDownLatch begin = new CountDownLatch(1);
        CountDownLatch end = new CountDownLatch(runSize);
        //循环创建线程
        for (int j = 0; j < runSize; j++) {
            List<CyryHistory> newlist = null;
            //计算每个线程执行的数据
            if ((j + 1) == runSize) {
                int startIndex = (j * count);
                int endIndex = list.size();
                newlist = list.subList(startIndex, endIndex);
            } else {
                int startIndex = (j * count);
                int endIndex = (j + 1) * count;
                newlist = list.subList(startIndex, endIndex);
            }
            //线程类
            //这里执行线程的方式是调用线程池里的executor.execute(mythead)方法。
            List<CyryHistory> finalNewlist = newlist;
            executor.execute(new Runnable() {
                @Override
                public void run() {
                    iCyryHistoryService.saveBatch(finalNewlist);
                    try {
                        begin.await();
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } finally {
                        //计数器减一的
                        end.countDown();
                    }
                }
            });
        }
        begin.countDown();
        end.await();
        //执行完关闭线程池
        executor.shutdown();
    }


    @GetMapping("/startCyHis")
    public boolean startCyHis() throws IOException, SQLException, InterruptedException {
        DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        sdf.setLenient(false);
        //获取mybatis
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

        //2. 获取SqlSession对象，用它来执行sql
        SqlSession sqlSession = sqlSessionFactory.openSession();
        CyryHistoryMapper mapper = sqlSession.getMapper(CyryHistoryMapper.class);
        List<CyryHistory> cyryHistories1 = mapper.selectAllLizhi();

        Long aLong = mapper.selectAllCount();
        sqlSession.close();

        Long l = (aLong / 20000) + 1;
        for (long i = 0; i < l; i++) {
            System.out.println("======================================" + 20000 * i + "==========" + 20000 * (i + 1));
            //2. 获取SqlSession对象，用它来执行sql
            SqlSession sqlSession1 = sqlSessionFactory.openSession();
            //3. 获取mapper
            CyryHistoryMapper cyryHistoryMapper = sqlSession1.getMapper(CyryHistoryMapper.class);
            List<CyryHistory> cyryHistories = cyryHistoryMapper.selectAll(20000 * i, 20000L);
            if (i == 0) {
                cyryHistories.addAll(cyryHistories1);
            }
            int listSize = cyryHistories.size();        //数据集合大小
            int runSize = 1;
            int count = listSize / 4;
            //开启的线程数
            //存放每个线程的执行数据
            ThreadPoolExecutor executor = new ThreadPoolExecutor(runSize, runSize,
                    30L, TimeUnit.SECONDS,
                    new LinkedBlockingQueue<Runnable>());
            //创建两个个计数器
            CountDownLatch begin = new CountDownLatch(1);
            CountDownLatch end = new CountDownLatch(runSize);
            //循环创建线程
            for (int j = 0; j < runSize; j++) {
                List<CyryHistory> newlist = null;
                //计算每个线程执行的数据
                if ((j + 1) == runSize) {
                    int startIndex = (j * count);
                    int endIndex = cyryHistories.size();
                    newlist = cyryHistories.subList(startIndex, endIndex);
                } else {
                    int startIndex = (j * count);
                    int endIndex = (j + 1) * count;
                    newlist = cyryHistories.subList(startIndex, endIndex);
                }
                //线程类
                // CyHisThread mythead = new CyHisThread(newlist, begin, end, iCyryHistoryService, cyryLabelMapper, iCyryLabelService);
                //这里执行线程的方式是调用线程池里的executor.execute(mythead)方法。
                // executor.execute(mythead);
            }
            begin.countDown();
            end.await();
            //执行完关闭线程池
            executor.shutdown();

            sqlSession1.close();
        }


        return true;
    }

}
